<?php
namespace util;

use exception\FriendlyException;
use OSS\Core\OssException;
use OSS\OssClient;

class AliOss {

    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录https://ram.console.aliyun.com创建RAM账号。
    private $accessKeyId = "<yourAccessKeyId>";
    private $accessKeySecret = "<yourAccessKeySecret>";
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private $endpoint = "http://oss-cn-shenzhen.aliyuncs.com";

    private $ossClient = null;
    private $bucket = null;

    public function __construct($accessKeyId, $accessKeySecret, $bucket) {  
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->bucket = $bucket;
    }

    public function getClient() {
        if($this->ossClient == null) {
            $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        }
        return $this->ossClient;
    }

    public function uploadFile($filePath, $ossName) {
        try {
            $ossClient = $this->getClient();
            $options = array(
                  OssClient::OSS_HEADERS => array(
                    "x-oss-forbid-overwrite" => "true",
            ));
            $ossClient->uploadFile($this->bucket, $ossName, $filePath, $options);
        } catch (OssException $th) {
            if(strpos($th->getMessage(), 'FileAlreadyExists') !== false) throw new FriendlyException('文件名不能重复');
            throw $th;
        }
    }

    public function deleteFile($ossName) {
        $ossClient = $this->getClient();
        $ossClient->deleteObject($this->bucket, $ossName);
    }

    public function download($ossName) {
        $ossClient = $this->getClient();
        $content = $ossClient->getObject($this->bucket, $ossName);
        return $content;
    }

}